from uuid import uuid4

from django.contrib.auth.models import AbstractUser, UserManager
from django.core.cache import cache
from django.db import models
from django.db.models import CharField, TextField, BooleanField, SET_NULL


class UserProfile(AbstractUser):
    """
    user models configured
    """
    objects = UserManager()
    username = CharField(max_length=150, unique=True, db_index=True, verbose_name='用户账号')
    secret = CharField(max_length=255, default=uuid4, verbose_name='加密秘钥')
    email = CharField(max_length=255, verbose_name="邮箱", null=True, blank=True)
    mobile = CharField(max_length=255, verbose_name="电话", null=True, blank=True)

    class Meta:
        verbose_name = '用户管理'
        verbose_name_plural = verbose_name

    @property
    def delete_cache(self):
        """
        清空缓存中的接口列表
        :return:
        """
        return cache.delete(f'permission_interface_dict_{self.username}')

    def __str__(self):
        if self.username:
            return f"{self.username}({self.mobile})"
        return f"{self.username}"


class LoginInfer(models.Model):
    """
    user login configured
    """
    session_id = CharField(max_length=64, verbose_name="会话标识", null=True, blank=True)
    browser = CharField(max_length=64, verbose_name="浏览器")
    ipaddr = CharField(max_length=32, verbose_name="ip地址", null=True, blank=True)
    loginLocation = CharField(max_length=64, verbose_name="登录位置", null=True, blank=True)
    msg = TextField(verbose_name="操作信息", null=True, blank=True)
    os = CharField(max_length=64, verbose_name="操作系统", null=True, blank=True)
    status = BooleanField(default=False, verbose_name="登录状态")
    creator = models.ForeignKey(to='UserProfile', related_query_name='creator_query', null=True,
                                verbose_name='创建者', on_delete=SET_NULL, db_constraint=False)

    class Meta:
        verbose_name = '登录日志'
        verbose_name_plural = verbose_name

    def __str__(self):
        return f"{self.creator and self.creator.username}"
